<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>综合服务系统--试题库首页</title>
    <!--公用样式-->
    <link rel="stylesheet" type="text/css" href="${re.contextPath}/plugin/common/css/comment.css"/>
    <link rel="stylesheet" type="text/css" href="${re.contextPath}/plugin/supplier/common/css/style.css"/>
    <!--Layui-->
    <link rel="stylesheet" href="${re.contextPath}/plugin/layui/css/layui.css" media="all"/>
    <!--extended-->
    <link rel="stylesheet" type="text/css" href="${re.contextPath}/plugin/common/css/extended.css"/>
    <link rel="stylesheet" href="/plugin/it/common/css/zTreeStyle/zTreeStyle.css" type="text/css">
    <link rel="stylesheet" href="${re.contextPath}/plugin/zTree/CSS/tree.css" type="text/css">
    <!--公用样式JS-->
    <script type="text/javascript" src="${re.contextPath}/plugin/jquery/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" charset="utf-8" src="${re.contextPath}/plugin/common/js/comment.js"></script>
    <script type="text/javascript" src="${re.contextPath}/plugin/layui/layui.js" charset="utf-8"></script>
    <script type="text/javascript" src="${re.contextPath}/plugin/zTree/js/jquery.ztree.all.js" charset="utf-8"></script>
</head>
<style>
    .Right {
        width: 100%;
        overflow-y: auto;
    }

    .project table tr th {
        background: #5775EF;
        color: #FFF;
    }

    .screening ul li > select {
        border-color: #DDDDDD;
        height: 38px;
    }

    .screening button {
        box-sizing: border-box;
        height: 38px;
    }
    .layui-table-grid-down{
        display: none;
    }

    .ztree li span {
        display: block;
        float: left;
        max-width: 70px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
    .ztree li span.button.switch.level2 {
        background-image: none;
    }

    .layui-laypage .layui-laypage-curr .layui-laypage-em {
        background: #5775EF;
    }

    .ztree li span.button.switch {
        position: relative;
        z-index: 10;
    }

    .layui-breadcrumb a:hover {
        color: #5775EF !important;
    }

    #leftbox {
        overflow: auto;
        position: relative;
        width: 25%;
        max-width: 250px
    }
</style>

<body style="overflow: hidden;">
<!--头部-->
<div style="background-color: #F1F4FB;padding-left: 20px;">
    <span class="layui-breadcrumb" lay-separator=">">
        <a><cite>考试管理</cite></a>
        <a href="#"><cite>试题库</cite></a>
    </span>
</div>
<!--容器-->
<div class="container clearfix df" style="height: 100vh;">
    <!--右侧内容-->
    <div class="Right fr fs14a" id="leftbox" style="">
        <div class="bcfff" id="righttree"
             style="width:90%;display:block;margin: 0 auto;border-radius: 10px;height: calc(100% - 60px);overflow: auto;">
            <div class="layui-container ztree w100p ofh ">
                <ul id="treeDemo"></ul>
            </div>
        </div>
        <div style="position: absolute;top: 40%;;right: 0;background: #FFF;border-radius: 0 4px 4px 0;"
             onclick="movehide()">
            <img src="/plugin/img/Right.png" style="width: 15px;height: 15px;"/>
        </div>
    </div>

    <div class="Right fr" style="overflow: auto;">
        <div class="screening  whitebg clearfix df" style="margin-top: 0;">
            <ul class="clearfix fl dff012">
                <li style="width: 30%;">
                    <div class="ask fl clearfix" style="width: 100%;">
                        <input type="text" class="widinput"
                               style="border: 1px solid #DDDDDD;width: 96%;box-sizing: border-box;height: 38px;"
                               name="content"
                               id="content" autocomplete="off" placeholder="输入关键字搜索">
                    </div>
                </li>
                <li style="width: 30%;">
                    <select name="quType" class="ml8 fl" id="quType"
                            style="width: 100%;padding-right: 0;padding-left: 5px"
                            lay-ignore>
                        <option value="">选择试题类型</option>
                        <#list sttx as vo>
                            <option value="${vo.badtCode}"
                            >${vo.badtName}</option>
                        </#list>
                    </select>
                </li>
                <li style="width: 23%;margin-left: 5px">
                    <select name="status" class="ml8 fl" id="status"
                            style="width: 100%;padding-right: 0;padding-left: 5px"
                            lay-ignore>
                        <option value="">选择状态</option>
                        <option value="001">已保存</option>
                        <option value="002">已提交</option>
                    </select>
                </li>
                <button type="button" class="bluebg white" style="width: 13%;margin-left: 5px;font-size: 14px;"
                        onclick="query()">搜索
                </button>
            </ul>
            <div class="fl dff1">
                <button type="button" class="white bluebg" style="width: 18.5%;float: right;font-size: 14px;"
                        onclick="add()">添加试题
                </button>
                <button type="button" class="c3e7ce7 bcfff"
                        style="width: 18.5%;float: right;margin-right: 10px;border: 1px solid #3e7ce7;font-size: 14px;"
                        onclick="dels()">
                    批量删除
                </button>
                <button type="button" class="c3e7ce7 bcfff"
                        style="width: 18.5%;float: right;margin-right: 10px;border: 1px solid #3e7ce7;font-size: 14px;"
                        onclick="submit()">批量提交
                </button>
                <button type="button" class="c3e7ce7 bcfff"
                        style="width: 18.5%;float: right;margin-right: 10px;border: 1px solid #3e7ce7;font-size: 14px;"
                        onclick="hsz()">
                    回收站
                </button>
            </div>
        </div>

        <div class="project whitebg">
            <table id="tableList" class="layui-hide" lay-filter="tableList"></table>
        </div>
    </div>
</div>
<script type="text/javascript" src="${re.contextPath}/plugin/tools/tool.js"></script>
<script type="text/javascript" charset="utf-8" src="${re.contextPath}/plugin/common/js/tabs.js"></script>
<script type="text/html" id="toolBarRow">
    <a class="layui-btn layui-btn-xs  layui-btn-normal" lay-event="edit" style="margin-left: 0;">编辑</a>
    <a class="layui-btn layui-btn-xs  layui-btn-normal" lay-event="derive" style="margin-left: 0;">导出试题</a>
    <a class="layui-btn layui-btn-xs  layui-btn-normal" lay-event="del" style="margin-left: 0;">删除</a>
</script>
<script type="text/javascript">
    var layer;
    var form;
    var table = null;
    var tableIns = null;
    //注意进度条依赖 element 模块，否则无法进行正常渲染和功能性操作
    var element;
    var laydate;
    layui.use(['element', 'laydate', 'table', 'form'], function () {
        element = layui.element;
        laydate = layui.laydate;
        form = layui.form
        //执行一个laydate实例
        laydate.render({
            elem: '#beginDate' //指定元素
        });
        laydate.render({
            elem: '#endDate' //指定元素
        });

    });

    //筛选
    function query() {
        var quType = $('#quType').val();
        var status = $('#status').val();
        var content = $('#content').val();
        var jsondata = {
            content: content,
            status: status,
            quType: quType,
        };
        table.reload('tableList', {where: jsondata});
    }

    layui.use('table', function () {
        table = layui.table;
        element = element;
        //方法级渲染
        tableIns = table.render({
            id: 'tableList',
            elem: '#tableList',
            url: '/ex/question/stkList',
            height: "auto",
            page: true,
            cols: [[
                {type: 'checkbox', fixed: 'fixed'},
                {
                    title: '序号', width: '8%', templet: function (res) {
                        return res.LAY_INDEX;
                    }, align: 'center'
                },
                {field: 'quId', title: 'ID', hide: true, sort: false},
                {field: 'content', title: '试题名称', width: '20%', sort: false},
                {field: 'quCategory', title: '试题分类', width: '14%', sort: false},
                {field: 'quType', title: '试题题型', width: '12%',},
                {field: 'level', title: '试题难度', width: '12%'},
                {
                    field: 'status', title: '状态', width: '12%', templet: function (d) {
                        if (d.status == "000") {
                            return '<span>已删除 </span>';
                        }
                        if (d.status == "001") {
                            return '<span style="color: red">已保存</span>';
                        }
                        if (d.status == "002") {
                            return '<span style="color: green">已提交</span>';
                        }
                    }
                },
                {field: 'remark', title: '操作', width: '20%', toolbar: "#toolBarRow", fixed: 'right'}
            ]],
            done: function (res, currentCount) {
                //***重点***：table渲染完成后渲染element进度条
                element.render();
                $(".layui-table-page select").css("width", "80px");
            }
        });

        //监听工具条
        table.on('tool(tableList)', function (obj) {
            let data = obj.data;
            if (obj.event === 'edit') {
                edit(data.quId);
            }
            if (obj.event === 'del') {
                del(data);
            }
            if (obj.event === 'derive') {
                derive(data.quId);
            }
        });

    });

    //删除（改状态 已提交不可删除）
    function del(data) {
        layer.confirm('删除,可在回收站中进行还原。', {btn: ['确定', '取消']}, function () {
            let json = {};
            if (data.status == '002') {
                json = {
                    quId: data.quId,
                    status: '000',
                    reductionType: '002'
                }
            }else {
                json = {
                    quId: data.quId,
                    status: '000',
                    reductionType: '001'
                }
            }

            layerAjaxGet("/ex/question/updateSt", json, '', function (d) {
                if (d) {
                    layer.msg("删除成功", {icon: 1});
                    tableIns.reload();
                } else {
                    layer.msg("删除失败", {icon: 2});
                }
            })
        });
    }

    //导出
    function derive(data) {
        location.href = '/ex/question/exportStk?quId=' + data;
    }

    //编辑
    function edit(data) {
        window.parent._showtab(data, '编辑试题', '/ex/question/stkUpdate?quId=' + data);
    }

    //批量删除（该状态 已提交不可删除）
    function dels() {
        let checkStatus = table.checkStatus('tableList');
        var data = checkStatus.data;
        if (data.length == 0) {
            layer.msg("至少选择一个删除", {icon: 2});
            return false;
        }
        layer.confirm('删除,可在回收站中进行还原。', {btn: ['确定', '取消']}, function () {
            let ids = [];
            for (let i = 0; i < data.length; i++) {
            /*    if (data[i].status == '002') {
                    layer.msg("已提交不可删除,请重新选", {icon: 2});
                    return;
                }*/
                ids.push(data[i].quId);
            }
            layerAjaxGet("/ex/question/updateSt", {ids: ids, state: '000'}, '', function (d) {
                if (d) {
                    layer.msg("删除成功 本次删除成功" + data.length + "条", {icon: 1});
                    tableIns.reload();
                } else {
                    layer.msg("删除失败", {icon: 2});
                }
            })
        });

    }

    //批量提交
    function submit() {
        var checkStatus = table.checkStatus('tableList');
        var data = checkStatus.data;
        if (data.length == 0) {
            layer.msg("至少选择一个提交", {icon: 2});
            return false;
        }
        layer.confirm('确定提交吗?', {btn: ['确定', '取消']}, function () {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
                if (data[i].status == '001') {
                    ids.push(data[i].quId);
                } else {
                    layer.msg("选中有已提交的数据,请重新选", {icon: 2});
                    return;
                }
            }
            layerAjaxGet("/ex/question/updateSt", {ids: ids, state: '002'}, '', function (d) {
                if (d) {
                    layer.msg("提交成功 本次提交成功" + data.length + "条", {icon: 1});
                    tableIns.reload();
                } else {
                    layer.msg("提交失败", {icon: 2});
                }
            })
        });
    }

    //新增页面跳转
    function add() {
        window.parent._showtab('cf8c85d3685a48abb23a4104ef32197c', '添加试题', '/ex/question/stkAdd');
    }

    //回收站
    function hsz() {
        window.parent._showtab('cf8c85d36852345b23a4104ef32197c', '回收站', '/ex/question/recycleBin');
    }

    /**树形下拉 **/

    var newCount = 1;   //这个属性是ztree添加节点的时候命名的依据（new node1、new node2）
    /***过滤条件****/
    function filter(node) {
        return (node.level == 0);
    }

    /*** 禁止拖动成为根节点 ****/
    function zTreeBeforeDrop(treeId, treeNodes, targetNode, moveType) {
        return !(targetNode == null || (moveType != "inner" && !targetNode.parentTId));
    }

    /******捕获异步加载正常结束,展开一级节点*******/
    function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
        var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
        var nodes = treeObj.getNodesByFilter(filter); // 查找节点集合
        if (nodes.length > 0) {
            for (var i in nodes) {
                treeObj.expandNode(nodes[i], true);
            }
        }
    }

    var setting = {
        treeId: "treeDemo",
        async: {
            enable: true,
            url: "/ex/question/selectTree",
            autoParam: ["id"],
            type: 'get'
        },
        callback: {
            onAsyncSuccess: zTreeOnAsyncSuccess,        //用于捕获异步加载正常结束的事件回调函数
            beforeRemove: beforeRemove,                 //用于捕获节点被删除之前的事件回调函数，并且根据返回值确定是否允许删除操作
            //用于捕获节点编辑名称结束（Input 失去焦点 或 按下 Enter 键）之后，更新节点名称数据之前的事件回调函数，并且根据返回值确定是否允许更改名称的操作
            beforeRename: beforeRename,
            onRemove: zTreeOnRemove,                    //用于捕获删除节点之后的事件回调函数。
            beforeDrop: zTreeBeforeDrop,                //用于捕获节点拖拽操作结束之前的事件回调函数，并且根据返回值确定是否允许此拖拽操作
            onDrop: zTreeOnDrop,                        //用于捕获节点拖拽操作结束的事件回调函数
            onClick: zTreeOnClick                       //用于捕获节点被点击的事件回调函数
        },
        data: {
            simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "pid"
            }
        },
        edit: {
            enable: true,
            editNameSelectAll: false,       //节点编辑名称 input 初次显示时,设置 txt 内容是否为全选状态
            removeTitle: "删除",
            renameTitle: "编辑",
            showRemoveBtn: showRemoveBtn,   //可根据实际业务需求控制是否显示 删除 按钮（方法返回true/false）
            showRenameBtn: showRenameBtn,   //可根据实际业务需求控制是否显示 编辑 按钮（方法返回true/false）
            drag: {
                autoExpandTrigger: true,    //拖拽时父节点自动展开是否触发 onExpand 事件回调函数
                isCopy: false,             //拖拽时, 设置是否允许复制节点  默认值：true
                isMove: false,              //拖拽时, 设置是否允许移动节点
                prev: true,                 //设置是否允许移动到目标节点前面的操作
                next: true,                 //设置是否允许移动到目标节点后面的操作
                inner: true,                //设置是否允许成为目标节点的子节点
                borderMax: 20,              //拖拽节点成为根节点时的 Tree 内边界范围 (单位：px)
                borderMin: -10,             //拖拽节点成为根节点时的 Tree 外边界范围 (单位：px)
                minMoveSize: 5,             //判定是否拖拽操作的最小位移值 (单位：px)
                maxShowNodeNum: 5,          //拖拽多个兄弟节点时，浮动图层中显示的最大节点数  多余的节点用...代替
                autoOpenTime: 0             //拖拽时父节点自动展开的延时间隔

            }
        },
        view: {
            addHoverDom: addHoverDom,               //鼠标滑过显示添加按钮
            removeHoverDom: removeHoverDom,         //鼠标滑过移除添加按钮
            dblClickExpand: true,
            txtSelectedEnable: true,
            showIcon: true,
            showLine: true,
            showTitle: true
        }
    }

    /***是否显示删除按钮 （flag是我后台自定义的节点属性，不是ztree的节点属性，可根据自己的业务自己定义其他条件）**/
    function showRemoveBtn(treeId, treeNode) {
        return treeNode.flag != '1' && treeNode.level != 0;
    }

    /***是否显示编辑按钮**/
    function showRenameBtn(treeId, treeNode) {
        return treeNode.flag != '1' && treeNode.level != 0;
    }

    //鼠标滑过取消显示添加按钮
    function removeHoverDom(treeId, treeNode) {
        $("#addBtn_" + treeNode.tId).unbind().remove();
    }

    /** 鼠标悬浮显示添加按钮 可根据实际业务判断是否显示添加按钮 flag是我后台自定义的节点属性，不是ztree的节点属性*/
    function addHoverDom(treeId, treeNode) {
        if (treeNode.level != '2') {
            var sObj = $("#" + treeNode.tId + "_span");
            if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
            var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
                + "' title='添加' οnfοcus='this.blur();'></span>";
            sObj.after(addStr);
            var btn = $("#addBtn_" + treeNode.tId);
            if (btn) btn.bind("click", function () {
                addNodes(treeNode);
                return false;
            });
        } else {
            return
        }
    }

    /***** 添加节点 直接与后台进行数据交互保存数据*****/
    function addNodes(treeNode) {
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        //这个方法是ztree添加节点的方法
        var name = "新建";   //名称
        var parentRoleId = treeNode.id;
        var param = {name: name, parentRoleId: parentRoleId};
        layerAjaxGet("/ex/question/insertTree", param, '', function (d) {
            if (d.flag) {
                layer.msg("添加成功!", {icon: 1});
                zTree.addNodes(treeNode, 0, {id: d.data, pId: treeNode.id, name: name});
                zTree.editName(treeNode.children[0])
            } else {
                layer.msg("系统异常", {icon: 2})
            }
        })
    }

    /*** 重命名 可根据业务需求控制能否进行重命名，可直接与后台进行数据交互**/
    function beforeRename(treeId, treeNode, newName) {
        if (newName.length == 0) {
            setTimeout(function () {
                var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                zTree.cancelEditName();
                // 这个是样式上删除
                zTree.removeNode(treeNode);
                // 交互删除
                zTreeOnRemove(treeNode);
                alert("节点名称不能为空.");
            }, 0);
            return;
        }
        var n=/^[\u4e00-\u9fa5]+$/i;
/*        if(!n.test(newName)){
            layer.msg("请输入汉字！", {icon: 2});return false;
        }*/
        // var name=newName.match(/[\u4E00-\u9FA5]/g).length;
        var name=newName.length;
        if(name>20){
            layer.msg("名称不能超过20个字符！", {icon: 2});return false;
        }
        var id = treeNode.id;
        var param = {name: newName.trim(), id: id};
        layerAjaxGet("/ex/question/updateTree", param, '', function (d) {
            if (d.flag) {
                layer.msg("编辑成功!", {icon: 1});
                $("#name").val(newName);
            } else {
                layer.msg("系统异常", {icon: 2})
            }
        })
        return true;
    }

    //ztree删除节点成功后（样式上删除，实际没有走后台删除数据）走这个方法，与后台交互删除数据
    function zTreeOnRemove(treeNode) {

        var id = treeNode.id;
        layerAjaxGet("/ex/question/deleteTree", {id: id}, '', function (d) {
            if (d.flag) {
                // layer.msg("编辑成功!", {icon: 1});
                layer.msg("已删除!", {icon: 1});
                var ids = $("#id").val();
                if (id == ids) {
                    $("#info").css('display', "none");
                }
            } else {
                if(d.msg){
                    layer.msg(d.msg, {icon: 2})
                }else{
                    layer.msg("系统异常", {icon: 2})
                }
            }
        })

    }

    //ztree删除节点之前判断是否允许删除节点（这个方法做了一些修改，因为ztree自带的弹窗不是很美观好用）
    function beforeRemove(treeId, treeNode) {
        // console.log(treeNode);
        if (treeNode.level == '0') {
            layer.msg("根节点不能删除!", {icon: 2});
            return false;
        }
        let id=treeNode.id;
        //判断节点是否被引用
        layerAjaxGet("/ex/question/deleteHint", {id: id}, '', function (d) {
            if (d.flag) {
                layer.confirm("确认删除" + treeNode.name + "吗?", {
                    btn: ['确定', '取消'] //按钮
                }, function () {
                    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                    zTree.removeNode(treeNode);
                    zTreeOnRemove(treeNode);
                    layer.closeAll()
                })
            }else {
                if(d.msg){
                    layer.msg(d.msg, {icon: 2});
                }else{
                    layer.msg("系统异常", {icon: 2});
                }
                return false;
            }
        })
        return false;
    }

    //拖动节点成功后与后台进行数据交互的方法
    function zTreeOnDrop(event, treeId, treeNodes) {
        if (treeNodes[0].level == '0') {
            layer.msg("根节点不能移动!", {icon: 2});
            return false;
        }
        var node = treeNodes[0];
        var id = node.ids;                 //id
        var param = {id: id};
        $.ajax({
            url: "/ucRole/update",
            type: "post",
            dataType: "json",
            async: true,
            data: param,
            success: function (data) {
                if (data.code == 200) {
                    layer.msg("移动成功!", {icon: 1});
                }
            },
            error: function () {
                layer.msg("系统异常", {icon: 2})
            }
        })
    }

    let rt = $('#righttree');
    let lb = $('#leftbox');
    let maxw = rt.width();
    let maxlw = lb.width();
    // 点击收放树列表
    function movehide() {
        let w;
        let lw;
        if (rt.css('display') === 'block') {
            w = maxw;
            lw = maxlw;
            lb.css('min-width', '0');
            index = setInterval(() => {
                lw -= 5;
                if (lw <= 15) {
                    rt.css('display', 'none');
                    clearInterval(index);
                    tableIns.reload();
                } else {
                    lb.width(lw + 'px');
                }
            }, 1)
        } else {
            w = rt.width();
            lw = lb.width();
            console.log(w);
            rt.css('display', 'block');
            index = setInterval(() => {
                lw += 5;
                if (lw >= maxlw) {
                    lb.css('min-width', '234px');
                    clearInterval(index);
                    tableIns.reload();
                } else {
                    lb.width(lw + 'px');
                }
            }, 1)
        }
    }

    $(document).ready(function () {
        $.fn.zTree.init($("#treeDemo"), setting);
    })

    //点击节点触发的方法，可以在里面写自己的业务逻辑（比如说数据的展示）
    function zTreeOnClick(event, treeId, treeNode) {
        var id = treeNode.id;
        var jsondata = {
            quCategory: id,
        };
        // table.reload('tableList', {where: jsondata},{page: curr});
        table.reload('tableList', {
            where: jsondata,
            page: {
                curr: 1 //重新从第 1 页开始
            },
        });
    }
</script>
</body>

</html>
